<template>
  <div class="card">
    <div
      class="title"
      :style="{
        width: lr === 'l' ? titleL : titleR
      }"
    >
      {{ title }}
      <span class="add-plan" v-if="add && tasks.length > 0" @click="complete()"
        >一键完成</span
      >
      <span class="add-plan" v-if="add" @click="addPlan()"> 添加任务</span>
    </div>
    <ul class="list" v-if="tasks.length > 0">
      <li v-for="(item, index) in tasks" :key="index" @click="addPlan(item)">
        <div class="task-name">{{ item.taskName }}</div>
        <div class="info">
          <div class="task-type">
            任务类型:<span class="type"
              >{{
                item.type == 0
                  ? '周期任务'
                  : item.type == 1
                  ? '空降任务'
                  : '自定义任务'
              }}
            </span>
          </div>
          <div class="task-number">
            任务编号:<span class="number">{{
              item.number ? item.number : '无'
            }}</span>
          </div>

          <div class="task-plan">
            任务进度:<span class="plan">{{ item.plan }}</span>
          </div>
        </div>
      </li>
    </ul>
    <div v-else :style="empty">
      <!-- 昨日逾期/本月延期/本月逾期 -->
      <img
        @click="addPlan()"
        :style="emptyImgStyle"
        v-if="title === cardTitle.today || title === cardTitle.week"
        :src="require('@/assets/imgs/plan/add.png')"
        alt=""
      />
      <!-- 今日计划/本周计划 -->
      <img
        :style="emptyImgStyle"
        v-if="
          title === cardTitle.yesterday ||
          title === cardTitle.overdue ||
          title === cardTitle.postpone
        "
        :src="require('@/assets/imgs/plan/complete.png')"
        alt=""
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="30%"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="taskForm.taskName" />
        </el-form-item>
        <el-form-item label="任务类型" prop="type">
          <el-select v-model="taskForm.type" placeholder="请选择任务类型">
            <el-option label="计划任务" :value="0" />
            <el-option label="临时任务" :value="1" />
            <el-option label="自定义任务" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="taskForm.type === 0" label="任务编号" prop="number">
          <el-input v-model="taskForm.number" />
        </el-form-item>
        <el-form-item
          v-if="dialogTitle === '修改任务'"
          label="任务进度"
          prop="plan"
        >
          <el-input
            v-model="taskForm.plan"
            placeholder="0～100"
            onkeyup="value=value.replace(/[^\d||/.]/g,'')"
            oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value>100){value=100}"
          >
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="taskForm.type && taskForm.type !== 0"
          label="任务描述"
          prop="taskDesc"
        >
          <el-input
            v-model="taskForm.taskDesc"
            type="textarea"
            placeholder="如:需求发起人，发起时间，关联人物编号等信息，用于任务追溯"
          />
        </el-form-item>
        <el-form-item
          v-if="isnoFinishDesc"
          :label="reasonName"
          prop="noFinishDesc"
        >
          <el-input
            v-model="taskForm.noFinishDesc"
            type="textarea"
            placeholder="务必说清楚当前操作的原因，用于任务追溯"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(taskFormRef)">取消</el-button>

          <el-button
            v-if="dialogTitle === '新增任务'"
            type="primary"
            @click="submitForm(taskFormRef)"
            >添加</el-button
          >
          <span v-else class="edit-btns">
            <el-button
              v-if="title === cardTitle.today || title === cardTitle.week"
              type="warning"
              @click="editTask(taskFormRef, '1')"
              >延期</el-button
            >
            <el-button type="danger" @click="editTask(taskFormRef, '2')"
              >删除</el-button
            >
            <el-button type="primary" @click="editTask(taskFormRef, '4')"
              >修改</el-button
            >
            <el-button type="success" @click="editTask(taskFormRef, '3')"
              >完成</el-button
            >
          </span>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { defineProps, ref, defineEmits, computed, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import api from '@/api'
import { whichDay, cardTitle, planType } from '@/utils/const/constant.js'

const dialogVisible = ref(false)
const props = defineProps({
  lr: {
    type: String,
    default: 'l'
  },
  title: {
    type: String,
    default: '标题'
  },
  tasks: {
    type: Array,
    default: () => []
  },
  add: {
    type: Boolean,
    default: false
  }
})
const store = useStore()

// 根据 卡片类型设置为空图片
const emptyImg = () => {
  let emptyImgStyle = {}
  let empty = {}

  if (props.title === cardTitle.today || props.title === cardTitle.week) {
    emptyImgStyle = {
      width: '100px',
      display: 'inline',
      position: 'relative',
      top: '15vh',
      cursor: 'pointer'
    }
  }
  if (props.title === cardTitle.yesterday) {
    emptyImgStyle = {
      width: '100px',
      display: 'inline',
      position: 'relative',
      top: '16vh'
    }
  }

  if (props.title === cardTitle.overdue || props.title === cardTitle.postpone) {
    emptyImgStyle = {
      width: '100px',
      display: 'inline',
      position: 'relative',
      top: '8vh'
    }
  }
  empty = {
    'text-align': 'center'
  }
  return { emptyImgStyle, empty }
}
const { emptyImgStyle } = emptyImg()
const { empty } = emptyImg()

const titleWidth = computed(() => {
  return store.getters.sidebarState
})
// 一键完成
const complete = () => {
  // 今天的
  let type = null
  if (props.title === cardTitle.today) {
    type = planType.today
  }
  // 本周的
  if (props.title === cardTitle.week) {
    type = planType.week
  }
  ElMessageBox.confirm(
    type === planType.today
      ? '当日所有任务已全部完成？'
      : '本周所有任务已全部完成?'
  ).then(() => {
    api.completeTasks({ planType: type }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          message: res.msg,
          type: 'success'
        })
      } else {
        ElMessage({
          message: res.msg,
          type: 'error'
        })
      }
    })

    emits('refreshData')
    isnoFinishDesc.value = false
    dialogVisible.value = false
  })
}

// 设置默认title宽度
const titleL = ref('')
const titleR = ref('')

if (store.getters.sidebarState) {
  titleL.value = '49.9%'
  titleR.value = '39.5%'
} else {
  titleL.value = '45.8%'
  titleR.value = '36.2%'
}

watch(titleWidth, (val) => {
  if (val) {
    titleL.value = '49.9%'
    titleR.value = '39.5%'
  } else {
    titleL.value = '45.8%'
    titleR.value = '36.2%'
  }
})

// 任务
const taskFormRef = ref(null)
const taskForm = ref({
  taskId: '',
  taskName: '',
  type: '',
  number: '',
  plan: 0,
  taskDesc: '',
  state: 0,
  isFinish: false,
  noFinishDesc: '',
  planType: null,
  whichDay: whichDay.today // 0:今天,1:昨天
})
const taskRules = {
  taskName: [
    { required: true, message: '任务名称不能为空', trigger: 'blur' },
    { min: 4, message: '任务名称不少于四位', trigger: 'blur' }
  ],
  type: [
    {
      required: true,
      message: '请选择任务类型',
      trigger: 'change'
    }
  ],
  taskDesc: [
    {
      required: true,
      message: '请输入,任务简述，发起人，关联编号等信息，用于任务追溯',
      trigger: 'blur'
    }
  ],
  number: [{ required: true, message: '任务编号不能为空', trigger: 'blur' }],
  plan: [{ required: true, message: '0～100', trigger: 'blur' }],
  noFinishDesc: [{ required: true, message: '请填写延期原因', trigger: 'blur' }]
}
const emits = defineEmits(['refreshData'])
// 提交表单
const submitForm = async (formEl) => {
  isnoFinishDesc.value = false
  if (!formEl) return
  // 区分提交的是每日还是每周
  if (props.title === cardTitle.today) {
    // 添加今日工作内容
    taskForm.value.planType = planType.today
  }
  if (props.title === cardTitle.week) {
    // 添加本周工作呢绒
    taskForm.value.planType = planType.week
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      api.addTask(taskForm.value).then((res) => {
        if (res.code === 200) {
          emits('refreshData')
          ElMessage({
            message: res.msg,
            type: 'success'
          })
          // 更新数据
        } else {
          ElMessage({
            message: res.msg,
            type: 'error'
          })
        }
      })
      dialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 重置表单
const resetForm = (formEl) => {
  dialogVisible.value = false
  isnoFinishDesc.value = false
  if (!formEl) return
  formEl.resetFields()
}
// 新增/编辑计划
const addPlan = (item = {}) => {
  console.log('咋回事?', item)
  if (Object.keys(item).length < 1) {
    dialogTitle.value = '新增任务'
  } else {
    dialogTitle.value = '修改任务'
  }
  dialogVisible.value = true

  // 回显示
  taskForm.value = { ...item }
}
const dialogTitle = ref('新增任务')
const handleClose = (done) => {
  ElMessageBox.confirm('确认放弃编辑？')
    .then(() => {
      isnoFinishDesc.value = false
      done()
    })
    .catch(() => {
      // catch error
    })
}
// 放弃/延期
const isnoFinishDesc = ref(false)
// 名称
const reasonName = ref('')
const editTask = async (formEl, type) => {
  // 确认修改哪一天
  if (props.title === cardTitle.today) {
    taskForm.value.whichDay = whichDay.today
    taskForm.value.planType = planType.today
  } else if (props.title === cardTitle.yesterday) {
    taskForm.value.whichDay = whichDay.yesterday
  } else if (props.title === cardTitle.week) {
    // 本周
    taskForm.value.planType = planType.week
  } else {
    taskForm.value.whichDay = whichDay.currentMonthDay
    taskForm.value.planType = planType.today
  }
  if (type === '1') {
    reasonName.value = '延期原因'
    taskForm.value.state = 1
  }
  if (type === '2') {
    reasonName.value = '删除原因'
    taskForm.value.state = 2
  }
  // 延期或者放弃
  if (isnoFinishDesc.value && (type === '1' || type === '2')) {
    // 提交放弃/延期
    await formEl.validate((valid, fields) => {
      if (valid) {
        ElMessageBox.confirm(`确定要${reasonName.value.substring(0, 2)}任务吗?`)
          .then(() => {
            api.editTask(taskForm.value).then((res) => {
              if (res.code === 200) {
                ElMessage({
                  message: res.msg,
                  type: 'success'
                })
              } else {
                ElMessage({
                  message: res.msg,
                  type: 'error'
                })
              }
            })

            emits('refreshData')
            isnoFinishDesc.value = false
            dialogVisible.value = false
          })
          .catch(() => {
            // catch error
          })
      }
    })
  } else {
    isnoFinishDesc.value = true
  }
  // 完成
  if (type === '3') {
    isnoFinishDesc.value = false
    await formEl.validate((valid, fields) => {
      if (valid) {
        ElMessageBox.confirm('确认该任务进度已经100%？').then(() => {
          // 进度100%
          taskForm.value.plan = 100
          // 完整状态true
          taskForm.value.isFinish = true
          api.editTask(taskForm.value).then((res) => {
            console.log('修改结果', res)
            if (res.code === 200) {
              ElMessage({
                message: res.msg,
                type: 'success'
              })
            } else {
              ElMessage({
                message: res.msg,
                type: 'error'
              })
            }
          })
          emits('refreshData')
          dialogVisible.value = false
        })
      }
    })
  }
  // 修改
  if (type === '4') {
    // 进度100 状态改成完成
    isnoFinishDesc.value = false
    await formEl.validate((valid, fields) => {
      if (valid) {
        ElMessageBox.confirm('确认修改？').then(() => {
          api.editTask(taskForm.value).then((res) => {
            console.log('修改结果', res)
            if (res.code === 200) {
              ElMessage({
                message: res.msg,
                type: 'success'
              })
            } else {
              ElMessage({
                message: res.msg,
                type: 'error'
              })
            }
          })
          emits('refreshData')
          isnoFinishDesc.value = false
          dialogVisible.value = false
        })
      }
    })
  }
}
</script>
<style lang="scss" scoped>
.edit-btns {
  padding-left: 12px;
}
.card {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  border-radius: 6px;
  position: relative;
  .title {
    padding: 10px 20px;
    border-bottom: solid 1px #e4e7ed;
    border-radius: 6px 6px 0 0;
    font-size: 14px;
    font-weight: 500;
    position: fixed;
    background-color: white;
    .add-plan {
      display: inline-block;
      float: right;
      margin-right: 10px;
      cursor: pointer;
      &:nth-child(2) {
        color: #409eff;
      }
      &:nth-child(1) {
        color: #67c23a;
      }
    }
  }
  .list {
    padding: 20px;
    padding-top: 50px;
    li {
      margin: 8px auto;
      border-top: 1px solid #e4e7ed;
      padding: 20px;
      cursor: pointer;
      &:hover {
        background-color: #f4f4f5;
      }
      &:first-child {
        margin-top: 0;
        border-top: none;
      }
      .task-name {
        font-size: 18px;
        color: rgb(48, 65, 86);
      }

      .info {
        display: flex;
        margin-top: 10px;
        font-size: 14px;
        .task-number,
        .task-plan {
          margin-left: 40px;
          font-weight: 600;

          .number {
            margin-left: 4px;
          }
          .plan {
            margin-left: 4px;
            color: red;
          }
        }

        .task-type {
          font-weight: 600;
          .type {
            color: orange;
            display: inline-block;
            margin-left: 4px;
          }
        }
      }
    }
  }
}
.warning {
  animation: glow 800ms ease-out infinite alternate;
}
@keyframes glow {
  0% {
    border-color: #ffe4e1;
    box-shadow: 0px 0px 3px 3px #ffe4e1;
  }
  100% {
    border-color: red;
    box-shadow: 0px 0px 3px 3px red;
  }
}

.month-plan {
  animation: wran 800ms ease-out infinite alternate;
}
@keyframes wran {
  0% {
    border-color: #ffe4e1;
    box-shadow: 0px 0px 3px 3px #ffe4e1;
  }
  100% {
    border-color: orange;
    box-shadow: 0px 0px 3px 3px orange;
  }
}
</style>
